package com.coldchain.cys.config.web;

import com.coldchain.authclient.interceptor.ServiceAuthRestInterceptor;
import com.coldchain.authclient.interceptor.UserAuthRestInterceptor;
import com.coldchain.common.handler.GlobalExceptionHandler;
import com.coldchain.cys.config.converter.DateConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.ConversionServiceFactoryBean;
import org.springframework.core.convert.ConversionService;
import org.springframework.core.convert.converter.Converter;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;

@Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter {

	/**
	 * 配置全局日期转换器
	 */
	@Bean
	@Autowired
	public ConversionService getConversionService(DateConverter dateConverter){
		ConversionServiceFactoryBean factoryBean = new ConversionServiceFactoryBean();
		Set<Converter> converters = new HashSet<Converter>();
		converters.add(dateConverter);
		factoryBean.setConverters(converters);
		return factoryBean.getObject();
	}

	@Bean
	GlobalExceptionHandler getGlobalExceptionHandler() {
		return new GlobalExceptionHandler();
	}

	@Override
	public void addInterceptors(InterceptorRegistry registry) {
		ArrayList<String> commonPathPatterns = getExcludeCommonPathPatterns();
		registry.addInterceptor(getServiceAuthRestInterceptor()).addPathPatterns("/**").excludePathPatterns(commonPathPatterns.toArray(new String[]{}));
		registry.addInterceptor(getUserAuthRestInterceptor()).addPathPatterns("/**").excludePathPatterns(commonPathPatterns.toArray(new String[]{}));
		super.addInterceptors(registry);
	}

	@Bean
	ServiceAuthRestInterceptor getServiceAuthRestInterceptor() {
		return new ServiceAuthRestInterceptor();
	}

	@Bean
	UserAuthRestInterceptor getUserAuthRestInterceptor() {
		return new UserAuthRestInterceptor();
	}


	private ArrayList<String> getExcludeCommonPathPatterns() {
		ArrayList<String> list = new ArrayList<>();
		String[] urls = {
				"/cys/v2/api-docs",
				"/v2/api-docs",
				"/swagger-resources/**"
		};
		Collections.addAll(list, urls);
		return list;
	}

	@Override
	public void addResourceHandlers(ResourceHandlerRegistry registry) {
		registry.addResourceHandler("/static/**")
		.addResourceLocations("classpath:/static/");
	}


}
